<template>
	<div class="login-container">
		<div class="login-box">
			<div class="login-form">
				<div class="login-lang">
					<Lang />
				</div>
				<el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" @keyup.enter="onLogin">
					<div class="login-title">
						<img src="@/assets/logo.png" />
						{{ $t('app.loginText') }}
					</div>
					<el-form-item prop="username">
						<el-input v-model="loginForm.username" :prefix-icon="User" :placeholder="$t('app.username')"></el-input>
					</el-form-item>
					<el-form-item prop="password">
						<el-input v-model="loginForm.password" autocomplete="new-password" :prefix-icon="Lock" show-password :placeholder="$t('app.password')"></el-input>
					</el-form-item>
					<el-form-item prop="captcha" class="login-captcha" v-if="false">
						<div class="flex1 flexL-C pr10">
							<div class="s-canvas w100" @click="createdCode">
								<canvas id="s-canvas" width="150" height="43"></canvas>
							</div>
							<!-- <img v-if="captchaImg" :src="captchaImg" @click="setCaptcha"/> -->
						</div>
						<el-input v-model="loginForm.captcha" :placeholder="$t('app.captcha')" :prefix-icon="Key" type="number"></el-input>
						<!-- <div class="login-captcha-div pointer" title="点击更换" @click="setCaptcha">
							<span>{{captcha1}}</span>
							<span>+</span>
							<span>{{captcha2}}</span>
						</div> -->
					</el-form-item>
					<el-form-item class="login-button">
						<el-button type="primary" @click="onLogin()" :loading="btnloading">{{ $t('app.signIn') }}</el-button>
						<!-- <el-button type="primary" @click="resetAdminUser()">初始化管理员用户</el-button> -->
					</el-form-item>
				</el-form>
			</div>
		</div>
		<Beian />
	</div>
</template>

<script setup lang="ts">
import { ref,onMounted } from 'vue'
import { User, Lock, Key } from '@element-plus/icons-vue'
import store from '@/store'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { Storage } from '@/utils/storage'
import { ElMessage } from 'element-plus'
import { encrypt, decrypt, spaceStrToString } from '@/utils/tool'
import { getUserPermission, postApi } from '@/api/api'
import axios from 'axios'
import { BASE_URL_BACK } from '@/config'
import Lang from '@/components/Lang/index.vue'
import Beian from '@/components/Beian/index.vue'

const resetAdminUser = () => {
	const params = {
		name: '系统管理员',
		phone: '13000000003',
		username: 'admin3',
		password: '123456',
		department_id: '1',
		type: 1
	}
	postApi('/admin/create',params , '').then(res => {
		console.log(res)
		if (res.code == 200) {
			ElMessage.success('初始化成功')
			loginForm.value.username = params.username
			loginForm.value.password = params.password
		} else {
			ElMessage.error(res.message)
		}
	}).catch(err => {
		ElMessage.error('初始化失败')
	})
}

const router = useRouter()
const { t } = useI18n()
const loginFormRef: any = ref(null)
const btnloading = ref(false)
const captchaImg: any = ref('')
const captchaTolen: any = ref('')
const clientWidthValue: any = ref(993)

const loginForm = ref({
	username: '',
	password: '',
	key: '',
	captcha: ''
})

onMounted(() => {
	clientWidthValue.value = document.body.clientWidth
	// setCaptcha()
	// createdCode()
	let login_tips = Storage.getItem('login_tips')
	let username = Storage.getItem('login_username')
	let password = Storage.getItem('login_password')
	if(login_tips){
		ElMessage.error(login_tips)
		Storage.removeItem('login_tips')
	}
	if(username){
		loginForm.value.username = decrypt(username)
		loginForm.value.password = decrypt(password)
	}
	// for (let index = 0; index < 100; index++) {
	// 	let jiami = encrypt(index+'');
	// 	// console.log('加密',jiami);
	// 	let urlas = encodeURIComponent(jiami);
	// 	// console.log('转为链接',urlas);
	// 	let jiemi = decrypt(spaceStrToString(urlas))
	// 	// console.log('解密后',jiemi);
	// }
})
// 切换登录界面
const changeLoginPage = () => {
	router.push({ path: '/login' })
}
// 更新验证码
const setCaptcha = () => {
	axios.get(BASE_URL_BACK+'/captcha/api/math').then((res: any) => {
		if(res.status == 200){
			captchaImg.value = res.data.img
			captchaTolen.value = res.data.key
			loginForm.value.key = res.data.key
		} else {
			ElMessage.error(res.message || res.data || 'error')
		}
	}).catch((err: any) => {
		console.log(err)
	})
}

const loginRules = ref({
	username: [{ required: true, message: t('required'), trigger: 'blur' }],
	password: [{ required: true, message: t('required'), trigger: 'blur' }],
	captcha: [{ required: true, message: t('required'), trigger: 'blur' }]
})

const onLogin = () => {
	loginFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
		// if(Number(loginForm.value.captcha) != (Number(identifyCode1.value) + Number(identifyCode2.value))){
		// 	createdCode()
		// 	ElMessage.error(t('error.captcha'))
		// 	return
		// }
		btnloading.value = true
		// 用户登录
		store.userStore.loginAction({
			strator_account: loginForm.value.username,
			strator_password: loginForm.value.password
		}).then(() => {
			router.push({ path: '/pagehome/index/index' })
			// getUserPermission({ id: decrypt(Storage.getItem('router_key')) })
			// .then((res: any) => {
			// 	const firstPage = res.data.findIndex((item: any) => item.route && item.route != '/')
			// 	console.log(firstPage)
			// 	if(firstPage != -1 && res.data.length > 0){
			// 		Storage.setItem('login_username',encrypt(loginForm.value.username))
			// 		Storage.setItem('login_password',encrypt(loginForm.value.password))
			// 		let redirect: any = router.currentRoute.value.query.redirect
			// 		if(redirect != '/nopage' && redirect != '/404'){
			// 			const canView = res.data.findIndex((item: any) => redirect == '/'+item.route)
			// 			if(canView != -1){
			// 				router.push({ path: redirect || '/' })
			// 			}else{
			// 				router.push({ path: '/' })
			// 			}
			// 		}else {
			// 			router.push({ path: '/' })
			// 		}
			// 	}else{
			// 		router.push({ path: '/nopage' })
			// 	}
				
			// })
			// .catch(() => {})
		}).catch(() => {
			// // .console.log(err);
			// setCaptcha()
			btnloading.value = false
		})
	})
}
const identifyCode1: any = ref('')
const identifyCode2: any = ref('')
const identifyCode: any = ref('')
// 生成随机计算数
const createdCode = () => {
	const chars = '123456789'
	const charsLen = chars.length
	identifyCode1.value = chars.charAt(Math.floor(Math.random() * charsLen))
	identifyCode2.value = chars.charAt(Math.floor(Math.random() * charsLen))
	identifyCode.value = identifyCode1.value + '+' + identifyCode2.value
	drawPic()
}

// 生成一个随机数
const randomNum = (min: any, max: any) => {
	return Math.floor(Math.random() * (max - min) + min)
}
// 生成一个随机的颜色
const randomColor = (min: any, max: any) => {
	const r = randomNum(min, max)
	const g = randomNum(min, max)
	const b = randomNum(min, max)
	return 'rgb(' + r + ',' + g + ',' + b + ')'
}

const drawPic = () => {
	const canvas: any = document.getElementById('s-canvas')
	const ctx = canvas.getContext('2d')
	ctx.textBaseline = 'bottom'
	// 绘制背景
	ctx.fillStyle = randomColor(255, 255)
	ctx.fillRect(0, 0, 150, 43)
	// 绘制文字
	drawText(ctx, identifyCode.value[0], 0, true)
	drawText(ctx, identifyCode.value[1], 1, false)
	drawText(ctx, identifyCode.value[2], 2, true)
	drawLine(ctx)
	drawDot(ctx)
}

const drawText = (ctx: any, txt: any, i: any, d: any) => {
	ctx.fillStyle = randomColor(0, 160)
	ctx.font = 'normal bold ' + randomNum(30, 36) + 'px SimHei'
	const x = (i + 1) * (150 / (identifyCode.value.length + 1))
	const y = randomNum(30, 43 - 5)
	var deg = d ? randomNum(-20, 20) : 0
	// 修改坐标原点和旋转角度
	ctx.translate(x, y)
	ctx.rotate((deg * Math.PI) / 180)
	ctx.fillText(txt, 0, 0)
	// 恢复坐标原点和旋转角度
	ctx.rotate((-deg * Math.PI) / 180)
	ctx.translate(-x, -y)
}

// 绘制干扰线
const drawLine = (ctx: any) => {
	for (let i = 0; i < 3; i++) {
		ctx.strokeStyle = randomColor(100, 255)
		ctx.beginPath()
		ctx.moveTo(randomNum(0, 150), randomNum(0, 43))
		ctx.lineTo(randomNum(0, 150), randomNum(0, 43))
		ctx.stroke()
	}
}

// 绘制干扰点
const drawDot = (ctx: any) => {
	for (let i = 0; i < 30; i++) {
		ctx.fillStyle = randomColor(0, 255)
		ctx.beginPath()
		ctx.arc(randomNum(0, 150), randomNum(0, 43), 1, 0, 2 * Math.PI)
		ctx.fill()
	}
}
</script>

<style lang="scss" scoped>
.login-container {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;
	width: 100%;
	background: url('@/assets/back2.png') no-repeat center;
	background-size: cover;
}
.login-box{
	display: flex;
	box-shadow: 1px 1px 5px #F07C55;
	box-sizing: border-box;
	border-radius: 8px;
	overflow: hidden;
}
.login-intro {
	display: flex;
	flex-direction: column;
	width: 800px;
	height:400px;
	img{
		width:100%;
		height:100%;
	}
}
.login-intro h1 {
	color: var(--el-color-primary);
}
.login-intro .desc {
	color: rgb(113, 115, 112);
	line-height: 32px;
	padding: 15px 0;
}
.login-bg img {
	width: 520px;
}
.login-form {
	width: 430px;
	height:400px;
	background-color: #fff;
	flex: 0 1 auto;
	padding: 5px 40px;
	box-sizing: border-box;
	position: relative;
	:deep(.el-input) {
		height: 45px;
		margin-top: 5px;
		.el-input__inner {
			padding: 10px 15px 10px 5px;
			height: 45px;
			line-height: 45px;
			color: #666;
			font-size: 16px;
		}
	}
	.login-lang{
		position: absolute;
		width: auto;
		height: auto;
		right: 10px;
		top: 10px;
		cursor: pointer;
	}
}
.login-title {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 90px;
	font-size: 24px;
	color: #444;
	letter-spacing: 4px;
	img{
		width:50px;
		margin-right: 10px;
	}
}
.login-captcha {
	.login-captcha-div{
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		span{
			margin: 0 12px;
		}
	}
	:deep(.el-input) {
		width: 180px;
	}
}
.login-captcha img {
	width: 150px;
	height: 43px;
	margin-top: 5px;
	cursor: pointer;
}
.login-button {
	:deep(.el-button--primary) {
		margin-top: 10px;
		width: 100%;
		height: 45px;
		font-size: 18px;
		// letter-spacing: 8px;
		&:hover{
			opacity: 0.8;
		}
	}
}
// 切换的过来
.changeLogin{
	position: fixed;
	right: 0;
	top: 0;
	width: 60px;
	height: 30px;
	display: flex;
	justify-content: center;
	align-items: center;
	cursor: pointer;
	img{
		width: 30px;
		height: 30px;
	}
	:deep(){
		.el-popper{
			min-width: 80px;
			height: 14px;
		}
	}
}
@media only screen and (max-width: 992px) {
	.login-intro {
		display: none;
	}
}
@media only screen and (max-width: 768px) {
	.login-container {
		background: #fff;
	}
	.login-intro {
		display: none;
	}
	.login-form {
		flex: 0 1 auto;
		border-radius: 0;
		box-shadow: none;
	}
	.login-captcha {
		:deep(.el-input) {
			width: 150px;
		}
	}
}
</style>
